<template>
  <el-row :gutter="20">
    <el-col :span="16">
      <ContentWrap title="申请信息">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="80px"
        >
          <el-form-item label="领用号" prop="receiveCode">
            <el-input v-model="formData.receiveCode" placeholder="请输入领用号" disabled />
          </el-form-item>
          
          <el-form-item label="申请标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入申请标题" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3" />
          </el-form-item>
          
          

        <el-tabs v-model="activeTab" class="mt-20px" type="border-card">
          <el-tab-pane label="领用明细" name="details">
            <div class="mb-10px">
              <el-button type="primary" @click="openDetailDialog">
                <Icon icon="ep:plus" /> 新增领用明细
              </el-button>
            </div>
            <el-table :data="detailList" style="width: 100%">
              <el-table-column label="物料名称" prop="materialName" />
              <el-table-column label="物料编码" prop="materialCode" />
              <el-table-column label="物料类型" prop="materialType">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.OA_MATERIAL_TYPE" :value="scope.row.materialType" />
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="quantity" />
              <el-table-column label="备注" prop="remarks" />
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button link type="primary" @click="editDetail(scope.row, scope.$index)">编辑</el-button>
                  <el-button link type="danger" @click="removeDetail(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 明细编辑弹窗 -->
            <el-dialog v-model="detailDialogVisible" title="编辑明细" width="500px">
              <el-form :model="detailForm" :rules="detailFormRules" ref="detailFormRef" label-width="80px">
                <el-form-item label="物料" prop="materialId">
                  <MaterialInfoSelect v-model="detailForm.materialId" :options="materialOptions" />
                </el-form-item>
                <el-form-item label="数量" prop="quantity">
                  <el-input-number v-model="detailForm.quantity" :min="1" />
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                  <el-input v-model="detailForm.remarks" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="detailDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitDetailForm">确定</el-button>
              </template>
            </el-dialog>
          </el-tab-pane>
        </el-tabs >
          <el-form-item class="mt-20px " align="center">
            <el-button :disabled="formLoading" class="w100px" @click="saveDraft">
              暂存
            </el-button>
            <el-button :disabled="formLoading" type="primary" class="w100px" @click="submitForm">
              审批
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
    </el-col>

    <!-- 审批相关：流程信息 -->
    <el-col :span="8">
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline
          ref="timelineRef"
          :activity-nodes="activityNodes"
          :show-status-icon="false"
          @select-user-confirm="selectUserConfirm"
        />
      </ContentWrap>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { MaterialReceiveApi, MaterialReceiveVO } from '@/api/oa/materialreceive'
import { useTagsViewStore } from '@/store/modules/tagsView'

// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'
import MaterialInfoSelect from '@/views/oa/materialinfo/MaterialInfoSelect.vue'
import { MaterialInfoApi } from '@/api/oa/materialinfo'

defineOptions({ name: 'OaMaterialReceiveCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const isDraftMode = ref(false) // 是否为编辑草稿模式
const formData = ref({
  id: undefined,
  receiveCode: undefined,
  userId: undefined,
  userName: undefined,
  deptId: undefined,
  deptName: undefined,
  title: undefined,
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
})
const formRules = reactive({
      title: [{ required: true, message: '申请标题不能为空', trigger: 'blur' }],
      status: [{ required: true, message: '审批结果不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

// 审批相关：变量
const processDefineKey = 'oa_material_receive' // 流程定义 Key
const startUserSelectTasks = ref([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')

/** 提交表单 */
const submitForm = async () => {
  // 1.1 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (detailList.value.length === 0) {
    message.error('请至少添加一条领用明细')
    return
  }

  // 1.2 校验明细中是否有重复的物料
  const materialIds = detailList.value.map(item => item.materialId)
  const uniqueMaterialIds = new Set(materialIds)
  if (materialIds.length !== uniqueMaterialIds.size) {
    message.error('领用明细中存在重复的物料，请检查后重新提交')
    return
  }

  // 1.3 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id]) &&
        startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择\${userTask.name}的审批人`)
      }
    }
  }

  // 2. 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value,
      detailList: detailList.value } as unknown as MaterialReceiveVO
    // 审批相关：设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
      data.startUserSelectAssignees = startUserSelectAssignees.value
    }
    await MaterialReceiveApi.createMaterialReceive(data)
    message.success('发起成功')
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'MaterialReceiveOwner' })
  } finally {
    formLoading.value = false
  }
}

/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      // TODO 小北：可以支持 processDefinitionKey 查询
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: JSON.stringify({ day: daysDifference() }) // 解决 GET 无法传递对象的问题，后端 String 再转 JSON
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {
  }
}

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

// 计算天数差
// TODO @小北：可以搞到 formatTime 里面去，然后看看 dayjs 里面有没有现成的方法，或者辅助计算的方法。
const daysDifference = () => {
  const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
  const diffTime = Math.abs(Number(formData.value.endTime) - Number(formData.value.startTime))
  return Math.floor(diffTime / oneDay)
}

/** 暂存操作 */
const saveDraft = async () => {
  // 1. 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (detailList.value.length === 0) {
    message.error('请至少添加一条领用明细')
    return
  }

  // 1.2 校验明细中是否有重复的物料
  const materialIds = detailList.value.map(item => item.materialId)
  const uniqueMaterialIds = new Set(materialIds)
  if (materialIds.length !== uniqueMaterialIds.size) {
    message.error('领用明细中存在重复的物料，请检查后重新保存')
    return
  }

  // 2. 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      detailList: detailList.value
    } as unknown as MaterialReceiveVO

    if (isDraftMode.value && formData.value.id) {
      // 编辑草稿
      await MaterialReceiveApi.updateDraft(data)
      message.success('暂存成功')
    } else {
      // 新增草稿
      await MaterialReceiveApi.saveDraft(data)
      message.success('暂存成功')
    }

    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'MaterialReceiveOwner' })
  } finally {
    formLoading.value = false
  }
}

/** 加载草稿数据 */
const loadDraftData = async (id: number) => {
  formLoading.value = true
  try {
    const data = await MaterialReceiveApi.getMaterialReceive(id)
    Object.assign(formData.value, data)
    detailList.value = data.detailList || []
    isDraftMode.value = true
  } finally {
    formLoading.value = false
  }
}

/** 初始化 */
onMounted(async () => {
  // 检查是否为编辑草稿模式
  const { query } = useRoute()
  if (query.id) {
    await loadDraftData(Number(query.id))
  }

  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )

  if (!processDefinitionDetail) {
    message.error('物品领用主的流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail()
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次, formData.value可改成实际业务中的特定字段 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    if (newValue && Object.keys(newValue).length > 0) {
      // 如果流程定义ID还未加载，则不调用审批详情（避免编辑草稿时报错）
      if (!processDefinitionId.value) {
        return
      }
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: true
  }
)


const activeTab = ref('details')
const detailList = ref<any[]>([])
const detailDialogVisible = ref(false)
const detailFormRef = ref()
const editDetailIndex = ref<number | null>(null)
const materialOptions = ref<any[]>([])

const detailForm = reactive({
  id: undefined,
  materialId: undefined,
  quantity: 1,
  remarks: ''
})
const detailFormRules = reactive({
  materialId: [{ required: true, message: '物料不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
})

onMounted(async () => {
  // 拉取物料选项
  const res = await MaterialInfoApi.getMaterialInfoPage({ pageNo: 1, pageSize: 1000 })
  materialOptions.value = res?.list || []
})

const openDetailDialog = () => {
  Object.assign(detailForm, { id: undefined, materialId: undefined, quantity: 1, remarks: '' })
  editDetailIndex.value = null
  detailDialogVisible.value = true
}
const editDetail = (row: any, index: number) => {
  Object.assign(detailForm, row)
  editDetailIndex.value = index
  detailDialogVisible.value = true
}
const removeDetail = (index: number) => {
  detailList.value.splice(index, 1)
}
const submitDetailForm = async () => {
  await detailFormRef.value.validate()
  // 1. 根据 materialId 找到选中的物料对象
  const material = materialOptions.value.find(item => item.id === detailForm.materialId)
  if (!material) {
    message.error('请选择物料')
    return
  }
  // 2. 组装明细对象，带上物料相关字段
  const detailData = {
    ...detailForm,
    materialId: detailForm.materialId,
    materialCode: material.materialCode,
    materialName: material.materialName,
    materialType: material.materialType
  }
  if (editDetailIndex.value !== null) {
    detailList.value.splice(editDetailIndex.value, 1, { ...detailData })
  } else {
    detailList.value.push({ ...detailData })
  }
  detailDialogVisible.value = false
  editDetailIndex.value = null
}

</script>
